//
//  MLHomeViewController.swift
//  MLWeiBo
//
//  Created by wenxing on 2017/1/4.
//  Copyright © 2017年 Se7venX. All rights reserved.
//

import UIKit


private let originalCellID:String = "cell1"
private let retweetedCellID:String = "cell2"


class MLHomeViewController: MLBaseTableViewController {
    
    
    //VM
    lazy var homeViewModel:MLHomeViewModel = MLHomeViewModel()
    
    //小菊花
    lazy var indicatorView:UIActivityIndicatorView = UIActivityIndicatorView()
    
    //小菊花
//    lazy var refreshControl:UIRefreshControl? = UIRefreshControl()
    lazy var mlRefreshControl:MLRefreshControl = MLRefreshControl()

    //MARK:- 生命周期 -
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setupUI()
        
        if isUserLogin==false {
            
            //设置访客视图的信息 --> 获取访客视图
            visitorView.updateInfo(title: "关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon",isHome: true)
        
            return
        }
        
        
        // tableview
        self.tableView.dataSource = self
        self.tableView.rowHeight = 700
        
        registerCell()
       
        // item
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", tatget: self, selector: #selector(clickSaoYiSao))
        
        configureRefreshControl()
        loadData()
        
    }
    
    
    //MARK:- 配置刷新控件 -
    private func configureRefreshControl() {
    
        //上拉
        tableView.tableFooterView = indicatorView
        
        //下拉
        //        tableView.tableHeaderView = self.refreshControl
//        self.refreshControl = UIRefreshControl()
//        self.refreshControl?.addTarget(self, action: #selector(refreshing), for: .valueChanged)

        tableView.addSubview(mlRefreshControl)
        mlRefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        
        
    }
    
    
    @objc private func refreshing() {

        
    }
    
    
    //MARK:- 加载数据 -
    func loadData() {
        // 请求数据
        homeViewModel.loadHomeData(isUp:indicatorView.isAnimating) { (isSuc,dtoCount) in
            
            if isSuc == false {
                
                print("请求错误")
                return
            }
            
            print("请求成功")
            
            if self.indicatorView.isAnimating == true {
            
                self.indicatorView.stopAnimating()
            }
            
//            if self.refreshControl?.isRefreshing == true {
//            
//                self.refreshControl?.endRefreshing()
//            }
            
            self.mlRefreshControl.endRefreshing()
            
            self.tableView.reloadData()
            
        }
        
    }
    
    //MARK:- 设置刷新 -
    private func setupUI() {
        
        indicatorView.sizeToFit()
        indicatorView.color  = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
        
     }

    
    private func registerCell() {
    
//        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

        let nib1 = UINib(nibName: "MLSatusCell", bundle: nil)
        self.tableView.register(nib1, forCellReuseIdentifier: originalCellID)
        
        let nib2 = UINib(nibName: "MLRetweetSatusCell", bundle: nil)
        self.tableView.register(nib2, forCellReuseIdentifier: retweetedCellID)
    
    }
    
    @objc private func clickSaoYiSao() {
    
        let sao = MLSaoYiSaoViewController()
        
        self.navigationController?.pushViewController(sao, animated: true)
    }
    
    //MARK:- UITableViewDataSource -
    override func numberOfSections(in tableView: UITableView) -> Int {
    
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    
        return homeViewModel.viewModelArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        
        let viewmodel = homeViewModel.viewModelArray[indexPath.row]
    
        let cellID = choodseCellID(viewmodel: viewmodel)
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! MLSatusCell
        
        cell.statusViewModel = viewmodel;
        
        
       return cell
    
    }
    /// 选择 cellID
    private func choodseCellID(viewmodel:MLStatusViewModel) -> String {
    
        
        return viewmodel.status?.retweeted_status == nil ? originalCellID : retweetedCellID
    }
    
    /// 选择xib的名字
    private func choodseXIBName(viewmodel:MLStatusViewModel) -> String {
        
        return viewmodel.status?.retweeted_status == nil ? "MLSatusCell" : "MLRetweetSatusCell"
    }
    
    //MARK:- UITableViewDelegate -
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
         let viewmodel = homeViewModel.viewModelArray[indexPath.row]
        
        let nib = UINib(nibName: choodseXIBName(viewmodel: viewmodel), bundle: nil)
        
        let cell = nib.instantiate(withOwner: nil, options: nil).last as! MLSatusCell
        
        
        cell.statusViewModel = viewmodel
        
        cell.layoutIfNeeded()
        
        return cell.toolBar.frame.maxY
        
    }
    
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        
        if indicatorView.isAnimating == false && indexPath.row == homeViewModel.viewModelArray.count-2 {
            
//            print("此处注意:::freshing")
            indicatorView.startAnimating()
//            loadData(isUp:true)
            
            loadData()
            
        }
        
        
    }
    
}

















